package com.jiepos.mpos.core.intercept;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import net.sf.json.JSONObject;
/**
 * 
* 描述: 自定义异常拦截
* 模块: 通用平台
* @author  娄伟峰
* @version 1.0
* @since 2012-5-17 下午5:40:36
* @history（历次修订内容、修订人、修订时间等）
 */
public class HandlerExceptionResolver extends SimpleMappingExceptionResolver{
	public HandlerExceptionResolver(){
		super();
	}
	/**
	 * 重写父类方法
	 */
	public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
		ex.printStackTrace();
		Logger log = LoggerFactory.getLogger(ex.getClass());
	//	 log.error(ex.getMessage());	
		log.error(getStackTrace(ex));
		
		
		// Expose ModelAndView for chosen error view.
		String viewName = determineViewName(ex, request);
		if (viewName != null) {
			// Apply HTTP status code for error views, if specified.
			// Only apply it if we're processing a top-level request.
			Integer statusCode = determineStatusCode(request, viewName);
			if (statusCode != null) {
				applyStatusCodeIfPossible(request, response, statusCode);
			}
			return getModelAndView(viewName, ex, request);
		}
		else {
			
			Map rspMap = new HashMap();			 
	/*		rspMap.put(SystemConstant.RSP_CODE, SystemConstant.RSPCODE_ERROR);		 
			Map dataMap = new HashMap();		 
			rspMap.put(SystemConstant.RSP_MSG,getStackTrace(ex));			 
			rspMap.put(SystemConstant.RSP_DATAMAP,null);*/
			response.setContentType("type=text/html;charset=UTF-8");  
	        String s = (JSONObject.fromObject(rspMap)).toString();  
	        try {
				response.getWriter().write(s);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return null;
		}
	}
	
	/**
     * 将异常堆栈转换为字符串
     * @param aThrowable 异常
     * @return String
     */
    public static String getStackTrace(Throwable aThrowable) {
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        aThrowable.printStackTrace(printWriter);
        return result.toString();
      }
}
